package jlfm.lastfm.apps.recorder;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import jlfm.lastfm.client.TrackMetadata;
import jlfm.lastfm.client.impl.stream.StreamHandlingException;

public class FileWritingStreamHandler extends
		AbstractStatusReportingStreamHandler {

	private FileNameProvider fileNameProvider;

	public FileWritingStreamHandler(FileNameProvider fileNameProvider) {
		this.fileNameProvider = fileNameProvider;
	}

	public boolean handleStreamIntern(TrackMetadata metadata, InputStream in)
			throws StreamHandlingException {

		return handleStream(fileNameProvider.getOutputFile(metadata), metadata,
				in);

	}

	public boolean handleStream(File outputFile, TrackMetadata m, InputStream in)
			throws StreamHandlingException {
		OutputStream out = null;
		try {
			createDirsIfNecessary(outputFile);
			out = new BufferedOutputStream(new FileOutputStream(outputFile));

			byte[] b = new byte[1024];
			int ret = 0;
			while ((ret = in.read(b)) > -1) {
				out.write(b, 0, ret);
			}
			out.close();

		} catch (IOException e) {
			throw new StreamHandlingException(e);
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return true;
	}

	private void createDirsIfNecessary(File outputFile) {
		if (outputFile.getParentFile() != null && !outputFile.getParentFile().exists()) {
			if (!outputFile.getParentFile().mkdirs()) {
				throw new StreamHandlingException(
						"Could not create needed directories for path: "
								+ outputFile.getParentFile());
			}
		}
	}

	public FileNameProvider getFileNameProvider() {
		return fileNameProvider;
	}

	public void setFileNameProvider(FileNameProvider fileNameProvider) {
		this.fileNameProvider = fileNameProvider;
	}

}
